<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-input
            size="medium"
            placeholder="请输入内容"
            v-model="params.query"
            clearable
            @clear="getUsersLists"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUsersLists"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button size="medium" type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 表格 -->
    <el-table :data="userList" style="width: 100%" border stripe>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="姓名" prop="username"></el-table-column>
      <el-table-column label="电话" prop="mobile"></el-table-column>
      <el-table-column label="角色" prop="role_name"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserInfos(scope.row.id)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserLists"></el-button>
          <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="userSettingRoles(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closeDiolog">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" >
            <el-form-item label="账号" prop="username">
                <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="mobile">
                <el-input v-model="ruleForm.mobile"></el-input>
            </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editUserDialog" width="50%" @close="closeEditUserDiolog">
      <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules">
          <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话号码" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer">
          <el-button @click="editUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="handelEditUserInfos(editForm)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 用户分配角色的对话框 -->
    <el-dialog title="用户分配角色" :visible.sync="userSettingRolesDialog" width="50%" @close="closeSetUserDiolog">
    <div>
      <p>当前用户名字:{{userInfos.username}}</p>
      <p>当前的角色:{{userInfos.role_name}}</p>
      <p>分配新的角色:
        <el-select v-model="selectRoleById" placeholder="请选择">
          <el-option
            v-for="item in roleLists"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </p>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="userSettingRolesDialog = false">取 消</el-button>
      <el-button type="primary" @click="querySetRoles">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 校验邮箱的验证规则
    var checkEmail = (rule, value, cb) => {
      // 验证表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9])+/
      if (regEmail.test(value)) {
        // 正确
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }

    // var checkMobile = (rule, value, cb) => {
    //   // 验证表达式
    //   const regMobile = /^(0|86|17951)?+(13[0-9]15[012356789]|17[678]18[0-9]14[57])[0-9]{8}$/
    //   if (regMobile.test(value)) {
    //     // 正确
    //     return cb()
    //   }
    //   cb(new Error('请输入合法的电话'))
    // }
    return {
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, message: '账号', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: false, message: '邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: false, message: '电话号码', trigger: 'blur' },
          {
            min: 11,
            max: 11,
            message: '长度在 11到 11 个字符',
            trigger: 'blur'
          }
        ]
      },
      params: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 对话框的显示与隐藏
      dialogVisible: false,
      //   显示和隐藏修改用户对话框
      editUserDialog: false,
      //   保存查询的用户数据
      editForm: {},
      //   修改表单验证规则
      editFormRules: {
        email: [
          { required: false, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: false, message: '请输入用户电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: '长度在 11到 11 个字符', trigger: 'blur' }
        ]
      },
      // 用户分配对话框的显示与隐藏
      userSettingRolesDialog: false,
      // 角色的数据列表
      roleLists: [],
      // 需要分配的用户信息
      userInfos: {},
      // 已选中的角色名称
      selectRoleById: ''
    }
  },
  methods: {
    async getUsersLists () {
      const { data: res } = await this.$http.get('users', {
        params: this.params
      })
      if (res.meta.status !== 200) { return this.$message.error('获取用户信息失败') }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize的改变
    handleSizeChange (newSize) {
      this.params.pagesize = newSize
      this.getUsersLists()
    },
    // 监听页码值的改变
    handleCurrentChange (newPage) {
      this.params.pagenum = newPage
      this.getUsersLists()
    },
    // 改变用户的状态
    async changeUserState (newInfo) {
      const { data: res } = await this.$http.put(
        `users/${newInfo.id}/state/${newInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        newInfo.mg_state = !newInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 关闭对话框
    closeDiolog () {
      this.$refs.ruleForm.resetFields()
    },
    // 添加用户
    submitForm (formName) {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('users', this.ruleForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUsersLists()
      })
    },
    // 修改用户
    async editUserInfos (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editForm = res.data
      this.editUserDialog = true
    },
    // 重置修改表单的内容
    closeEditUserDiolog () {
      this.$refs.editFormRef.resetFields()
    },
    // 验证表单数据的合法性
    handelEditUserInfos () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })

        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        // 关闭对话框
        this.editUserDialog = false
        // 刷新数据
        this.getUsersLists()
        // 提示成功信息
        this.$message.success('更新用户信息成功')
      })
    },
    // 删除用户数据
    async removeUserLists (id) {
      const confirmResult = await this.$messageBox.confirm('此操作将用就不删除此用户？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // .then(() => {
      //   const {data:res} = await this.$http.delete('users/' + id);
      //   if(res.meta.status !== 200){
      //       return this.$message.error('删除用户信息失败')
      //   }
      //   this.$message({
      //     type: 'info',
      //     message: '删除用户信息成功'
      //   })
      // })

      // {
      //   this.$message.info('已取消删除')
      // })
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户信息失败')
      }
      this.$message({
        type: 'info',
        message: '删除用户信息成功'
      })
      //   刷新页面
      this.getUsersLists()
    },
    // 用户分配角色
    async userSettingRoles (userInfos) {
      // 获取角色的数据

      this.userInfos = userInfos
      console.log(this.userInfos)

      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色数据失败')
      }

      this.roleLists = res.data
      console.log(this.roleLists)

      this.userSettingRolesDialog = true
    },
    // 确定分配角色
    async querySetRoles () {
      if (!this.selectRoleById) {
        return this.$message.error('请选择需要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfos.id}/role`, { rid: this.selectRoleById })

      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败')
      }

      this.$message.success('更新角色成功')
      this.getUsersLists()
      this.userSettingRolesDialog = false
    },
    // 关闭用户角色的分配对话框清空里面的默认内容
    closeSetUserDiolog () {
      this.userInfos = {}
      this.selectRoleById = ''
    }
  },
  created () {
    this.getUsersLists()
  }
}
</script>

<style lang="scss" scoped>
</style>
